import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Scrollbars } from 'react-custom-scrollbars';
import { Layout } from 'antd';

import CascaderSelectableMenus from '@/components/CascaderSelectableMenus';
import EnergySearch from '@/pages/energy/energySearch';
import EnergyRank from '@/pages/energy/energyRank';
import EnergyCompareSame from '@/pages/energy/energyCompare/same';
import EnergyCompareNext from '@/pages/energy/energyCompare/next';
import EnergyProportionTred from '@/pages/energy/energyProportion/trend';
import EnergySetting from '@/pages/energy/energySetting';
// import { ENERGYCATEGORY_PRICE } from '@/utils/constants';
import memoryUtils from '@/utils/memoryUtils';

import { initEnergyCategoryPrices } from '@/services/bajaService';


import styles from '@/pages/subSystem/index.less';
import { PageLoading } from '@ant-design/pro-layout';


const { Sider, Content } = Layout;

class index extends Component {

  static defaultProps = {
    pagePath: '/energysearch'
  }

  constructor(props) {
    super(props);
    const { treeMenus } = this.props;
    this.state = {
      $selectedHandle: (treeMenus&&treeMenus.length>0)?[treeMenus[0].$handle]:[],
      energyCategoryType: '',
      computeTypes: []
    }
  }

  getSearchParams = (treeMenus, $selectedHandle) => {
    let searchParamList = [];
    console.log("getSearchParams1", treeMenus, $selectedHandle);
    if(treeMenus && $selectedHandle && treeMenus.length > 0 && $selectedHandle.length > 0) {
      for(let i=0; i<treeMenus.length; i++) {
        if(treeMenus[i].$typeSpec.endsWith('MenuItem') && $selectedHandle.includes(treeMenus[i].$handle) && treeMenus[i].searchParams) {
          searchParamList.push(...treeMenus[i].searchParams);
        } else if(treeMenus[i].children && treeMenus[i].children.length > 0) {
          const searchParams = this.getSearchParams(treeMenus[i].children, $selectedHandle);
          searchParamList.push(...searchParams);
        }
      }
    }
    console.log("getSearchParams2", searchParamList);
    return searchParamList;
  }

  getSearchParamsValue = (searchParams) => {
    console.log("getSearchParamsValue", searchParams);
    const searchParamsValue = [];
    if (searchParams && searchParams.length > 0) {
      for (let i = 0; i < searchParams.length; i++) {
        if (searchParams[i].children) {
          searchParamsValue.push(...this.getSearchParamsValue(searchParams[i].children));
        } else {
          searchParamsValue.push(searchParams[i].title + '||' + searchParams[i].historyOrds.join('|||'));
        }
      }
    }
    return searchParamsValue;
  };

  getEnergyComponent = (pagePath, computeTypes, searchParamsValue, energyCategoryType='')=>{
    // this.props.dispatch({ type: 'energyStatistics/clearAll' });
    console.log("getEnergyComponent", searchParamsValue);
    if(pagePath.toLowerCase().startsWith('/energysearch')) {
      return <EnergySearch key={pagePath} searchParamsValue={searchParamsValue} energyCategoryType={energyCategoryType} computeTypes={computeTypes}/>;
    } else if(pagePath.toLowerCase().startsWith('/energyrank')) {
      return <EnergyRank key={pagePath} searchParamsValue={searchParamsValue} energyCategoryType={energyCategoryType} computeTypes={computeTypes}/>;
    } else if(pagePath.toLowerCase().startsWith('/energycomparesame')) {
      return <EnergyCompareSame key={pagePath} searchParamsValue={searchParamsValue} energyCategoryType={energyCategoryType} computeTypes={computeTypes}/>;
    } else if(pagePath.toLowerCase().startsWith('/energycomparenext')) {
      return <EnergyCompareNext key={pagePath} searchParamsValue={searchParamsValue} energyCategoryType={energyCategoryType} computeTypes={computeTypes}/>;
    } else if(pagePath.toLowerCase().startsWith('/energyproportiontred')) {
      return <EnergyProportionTred key={pagePath} searchParamsValue={searchParamsValue} energyCategoryType={energyCategoryType} computeTypes={computeTypes}/>;
    }
    return <></>;
  }

  handleSelectedMenuChange = ($selectedHandle, category)=>{
    console.log('handleSelectedMenuChange', $selectedHandle, category);
    this.setState({ $selectedHandle, energyCategoryType: category });
  }

  // componentWillReceiveProps(nextProps) {
  //   if(nextProps.pagePath !== this.props.pagePath) {
  //     this.setState({
  //       $selectedHandle: [],
  //       energyCategoryType: ''
  //     });
  //   }
  // }

  async componentDidMount() {
    // initEnergyCategoryPrices().then(categories=>{
    //   const computeTypes = [];
    //   categories.forEach((item)=>{
    //     // ENERGYCATEGORY_PRICE[item.energyCategoryType] = item.price;
    //     memoryUtils.ENERGYCATEGORY_PRICE[item.$handle] = item.price;
    //     computeTypes.push({label:item.title, value: item.$handle})
    //   });
    //   this.setState({computeTypes});
    // }).catch(e=>console.log('initEnergyCategoryPrices error', e));

    const categories = await initEnergyCategoryPrices();
    const computeTypes = [];
    categories.forEach((item)=>{
      memoryUtils.ENERGYCATEGORY_PRICE[item.$handle] = item.price;
      computeTypes.push({label:item.title, value: item.$handle})
    });
    this.setState({computeTypes});
  }

  render() {
    const {treeMenus, pagePath} = this.props;
    const { $selectedHandle, energyCategoryType, computeTypes} = this.state;
    if(!computeTypes || computeTypes.length == 0) {
      return <PageLoading/>;
    }
    const searchParamsValue = this.getSearchParamsValue(this.getSearchParams(treeMenus, $selectedHandle));
    if(pagePath.toLowerCase().startsWith('/energysetting')) {
      return <EnergySetting energyCategories={treeMenus}/>
    }
    console.log("render()", searchParamsValue);
    return (
      <Layout className={styles.subSystemPage}>
        <Layout>
          <Sider style={{backgroundColor: 'white', width: 300, maxWidth: 300, minWidth: 300}}>
            <CascaderSelectableMenus key={pagePath} treeMenus={treeMenus} onSelectedMenuChange={this.handleSelectedMenuChange} type={pagePath.startsWith('/energycompare')?'single':'multi'}/>
          </Sider>
          <Content className={styles.content} id={'handle'}>
            <Scrollbars autoHide id={'scroll'}>
              { this.getEnergyComponent(pagePath, computeTypes, searchParamsValue, energyCategoryType) }
            </Scrollbars>
          </Content>
        </Layout>
      </Layout>
    );
  }
}

index.propTypes = {
  treeMenus: PropTypes.array.isRequired,
  pagePath: PropTypes.string.isRequired
};

export default index;
